package common.util;

import cn.hutool.core.util.StrUtil;
import common.config.AppConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Set;

/**
 * 存储到内存里的工具类,具体是存储redis还是session要看需求.
 */
@Component
@Slf4j
public class CacheUtil {

    @Resource
    HttpSession session;

    public void saveObject(String key, Object value) {
        String accessId = UserUtil.getAccessId();
        if (StrUtil.isEmpty(accessId)) {
            session.setAttribute(key, value);
        } else {
            String redisKey = accessId + key;
            RedisUtil.saveObject(redisKey, value);
        }
    }

    public Object getObject(String key) {
        Object obj = null;
        String accessId = UserUtil.getAccessId();
        if (StrUtil.isEmpty(accessId)) {
            obj = session.getAttribute(key);
        } else {
            String redisKey = accessId + key;
            obj = RedisUtil.getObject(redisKey);
            if (RedisUtil.existsKey(redisKey)) {
                RedisUtil.resetExpire(redisKey, AppConfig.CACHE_EXPIRE_SECOND);
            }
        }
        return obj;
    }

    public Boolean existsKey(String key) {
        String accessId = UserUtil.getAccessId();
        if (StrUtil.isEmpty(accessId)) {
            Object obj = session.getAttribute(key);
            if (obj != null) {
                return true;
            }
        } else {
            String redisKey = accessId + key;
            return RedisUtil.existsKey(redisKey);
        }
        return false;
    }

    /**
     * 清楚用户相关的所有缓存
     */
    public Long clearUserCache() {
        String accessId = UserUtil.getAccessId();
        if (StrUtil.isEmpty(accessId)) {
            return 0L;
        }
        Set<String> set = RedisUtil.keys(accessId + "*");
        String[] array = set.toArray(new String[set.size()]);
        long total = RedisUtil.delKeys(array);
        return total;
    }

    public Long delKey(String key) {
        String accessId = UserUtil.getAccessId();
        String redisKey = accessId + key;
        long total = RedisUtil.delKeys(redisKey);
        return total;
    }

}